#include<stdio.h>
#include<malloc.h>
#include<stdbool.h>//bool:true\false
#include "link_stack.h"

/*初始化链栈*/
L_Stack_t* InitLinkStack(void)
{
    L_Stack_t *new_stack = (L_Stack_t *)malloc(sizeof(L_Stack_t));
    if (!new_stack)
    {
        return NULL;
    }
    
    new_stack->data = 0;
    new_stack->next = NULL;

    return new_stack;
}

/*销毁栈*/
void DestroyLinkStack(L_Stack_t **stack)
{
    if ((*stack) == NULL)
    {
        return;
    }

    L_Stack_t *current = *stack;
    while (current)
    {
        L_Stack_t *temp = current;
        free(current);
        current = temp->next;
    }
    
    free(*stack);
    *stack = NULL;
}

/*链栈入栈：头插*/
L_Stack_t* PushFront(L_Stack_t **stack, int data) {  
    L_Stack_t *new_top = (L_Stack_t *)malloc(sizeof(L_Stack_t));  
    if (!new_top) {  
        perror("Failed to allocate memory");  
        //exit(EXIT_FAILURE);  
    }  
    new_top->data = data;  
    new_top->next = *stack; 
    *stack = new_top; 
    printf("入栈元素为：%d\n", data);  
    return new_top;  
}  
  
  
/*链栈出栈：头删*/
int PopFront(L_Stack_t **stack) {  
    if (*stack == NULL) {  
        fprintf(stderr, "Stack is empty\n");  
        return -1;   
    }  
    L_Stack_t *temp = *stack;  
    int data = temp->data;  
    *stack = temp->next;  
    free(temp);  
    printf("出栈元素为：%d\n", data);  
    return data;  
}  


/*获取栈顶元素*/
int getTop(L_Stack_t **stack)
{
    if ((*stack) == NULL)
    {
        perror("NULL");
        exit(-1);
    }
    printf("栈顶元素为%d\n",(*stack)->data);
    return (*stack)->data;
    
}


L_Stack_t *stack = NULL;
int main(int argc, char const *argv[])
{

    stack = InitLinkStack();
    PushFront(&stack,1);
    PushFront(&stack,2);
    PushFront(&stack,3);
    PushFront(&stack,4);
    PushFront(&stack,5);
    PushFront(&stack,6);
    PopFront(&stack);
    PopFront(&stack);

    PushFront(&stack,20);
    PopFront(&stack);
    getTop(&stack);
    return 0;
}



